package kr.saeildamil.androidforstudy2.ch2930;

import kr.saeildamil.androidforstudy2.R;
import android.app.IntentService;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.widget.Toast;

public class NewsService extends IntentService {
	boolean mQuit;

	public NewsService() {
		super("NewsService");
	}

	@Override
	protected void onHandleIntent(Intent intent) {
		Message msg;
		// Log.d("NewsIntentService", "onHandleIntent");
		String[] arNews = getResources().getStringArray(R.array.desc);
		for (int i = 0; mQuit == false; i++) {
			msg = Message.obtain();
			msg.what = 0;
			msg.obj = arNews[i % arNews.length];
			mHandler.sendMessage(msg);
		try {
			Thread.sleep(5000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		}
	}

	Handler mHandler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			if (msg.what == 0) {
				Toast.makeText(NewsService.this, (String) msg.obj,
						Toast.LENGTH_SHORT).show();
			}
		}
	};

	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		// Log.d("NewsIntentService", "onStartCommand()");
		mQuit = false;
		return super.onStartCommand(intent, flags, startId);
	}

	@Override
	public void onDestroy() {
		// Log.d("NewsIntentService", "onDestroy()");
		super.onDestroy();
		mQuit = true;
	}
}
